

module('checkversion',package.seeall) 

gd_version={}  
local checkversionCCBLayer = {};
local m_updatevlist = nil;--版本更新列表
local m_text = nil;--显示版本检测情况
local m_btnOk = nil;--询问是否下载或出错重启的按钮
local m_versionindex = 1;--当前正在更新的更新包在更新列表中对应的序号
--表示操作的状态begin
local state_info = 0;
local state_loading = 1;
local state_error = 2;
local state_complete = 3;
local state_loadingres = 4;
local m_state = nil;
--end
local m_needwholeversion = nil;--冷更新标志
local m_timeindex=0;--计数器一直加，查小庸一直往前跑 
local m_totolsize = 0;--需要更新的包的总大小
local m_doaftercheckversion = nil;
local m_ccbnode = nil;
local m_process=nil;
local m_prosize=nil;
local winsize=cc.Director:getInstance():getWinSize()

--需要require的lua文件 

local lualist =
{
  function() require 'support/debug_version'end,
  function() require "support/common/Defines" end,
	function() require "support/util/LuaModuleExtend" end,
	function() require "support/util/pp" end,
	function() require "support/util/log" end,
	function() require "support/common/i18n" end,
	function() require "support/util/utf8" end,
	function() require "support/util/UIUtils" end,
	function() require "support/comm/Comm" end,
	function() require "support/common/Coroutine" end,
	function() require "support/common/GScheduler" end,
	function() require "support/login/LoginControl" end,
	function() require "support/public/MessageDialog" end,
	function() require "support/public/LoadingDialog" end,
	function() require "support/public/WaitingDialog" end,
	function() require "support/public/TipsDialog" end,
	function() require "support/public/RuleDialog" end,
	function() require "support/public/TouchInfoTips" end,
	function() require "support/common/ColorText" end,
	function() require "support/common/SceneManager" end,
	function() require "login/SpineControl" end,
	function() require "support/common/ubb/UBBLabel" end, 
}; 
			

      

--异步调用某个函数
local function nexttick(fun) 
  local scheshow = nil;
  local function show()
    if scheshow then
      gd_scheduler:unscheduleScriptEntry(scheshow);
    else
      return;
    end
    fun();
  end 
  scheshow = gd_scheduler:scheduleScriptFunc(show,0,false); 
end
local function startloading()
	local depverinfo = m_updatevlist[m_versionindex]
	local zipname = gd_godsliekithead .. depverinfo.versionstr .. '_v' .. depverinfo.version .. '_b' .. depverinfo.build .. '.zip';
	local url = ''; 
	--zip包全部放在了一个目录下，就不分服务器了
	if gd_testmode == '' then  
		--姑且当做走的是PP正式版本更新包吧 
		--url = 'http://192.168.5.215:8008/godslie/' .. zipname;--杰爷的
		url = 'http://wscdn.zs.9yuonline.com/godslie/' .. zipname;
	else 
		url = 'http://218.18.232.38:8000/godslie/' .. zipname;
	end 
	c_askZip(url);
end 
--版本列表中的版本按版本号排序
local function sortByVersion(a, b) 
  local aint = a.version
  local bint = b.version
  return aint < bint;
end  
--获取版本列表
function getVersionUrl(callback)  
  m_updatevlist=nil; 
  local xhr = cc.XMLHttpRequest:new()
  xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_STRING
  local url = ''; 
  --zip包全部放在了一个目录下，就不分服务器了
  if gd_testmode == '' then  
	--姑且当做走的是PP正式版本更新包列表吧 
	--url = 'http://192.168.5.215:8008/godslie/versionpp/versionlist.json';--杰爷的
	url = 'http://v.sz.9yuonline.com/godslie/versionpp/versionlist.json';
  else 
	url = 'http://218.18.232.38:8000/godslie/version' .. gd_testmode .. '/versionlist.json';
  end  
  xhr:open("GET", url)
  local function onReadyStateChange()
	if xhr.readyState == 4 and (xhr.status >= 200 and xhr.status < 207) then   
		local versionlist = json.decode(xhr.response) 
		table.sort(versionlist,sortByVersion);
		m_updatevlist = {}
		local curversionid = gd_version.version
		for i = 1,#versionlist do
			local versionid = versionlist[i].version 
			if versionid > curversionid then 
				--如果版本列表中有比当前正在玩的版本高级，就要更新版本了
				table.insert(m_updatevlist,versionlist[i]);
			end
		end  
	end 
	if m_updatevlist and #m_updatevlist>0 then 
		table.sort(m_updatevlist,sortByVersion);
	end
	callback(m_updatevlist and #m_updatevlist>0) 
  end
  xhr:registerScriptHandler(onReadyStateChange)
  xhr:send()  
end 
 
--开始检测版本
local function checkVersion() 
  local function callback(needupdate)
	if needupdate then 
		pb_data = json.encode(m_updatevlist);
		local wrt = cc.FileUtils:getInstance():getWritablePath();
		local path =wrt .. gd_hotupdatedir .. '/' .. gd_versionlistdir;
		local file = io.open(path, 'wb');
		if file then 
			file:write(pb_data);
			file:close();
		end      
		setState(state_info);
		return;
	end
	setState(state_loadingres)
  end
  getVersionUrl(callback);
end   
--版本检测的主UI
local function getCheckversion() 
  m_needwholeversion = false; 
  local ccbnode = cc.Layer:create() 
  m_ccbnode=ccbnode
  cc.SpriteFrameCache:getInstance():addSpriteFrames('res/login/login.plist')
  local bg=cc.Sprite:createWithSpriteFrameName('res/login/img_login_bg.png')
  bg:setPosition(cc.p(winsize.width/2,winsize.height/2))
  ccbnode:addChild(bg)
  local ttfConfig = {};
  ttfConfig.fontFilePath = "res/fonts/Arial.ttf"
  ttfConfig.fontSize = 24
  local blackbar=cc.LayerColor:create(cc.c4b(0,0,0,200))
  blackbar:setContentSize(cc.size(winsize.width,140))
  blackbar:setAnchorPoint(cc.p(0,0))
  blackbar:setPosition(cc.p(0,winsize.height/2-100))
  ccbnode:addChild(blackbar)
  local progbg=cc.Sprite:create('res/checkversion/progbg.png');
  progbg:setPosition(cc.p(winsize.width/2,winsize.height/2-50))
  ccbnode:addChild(progbg) 
  local prog=cc.Sprite:create('res/checkversion/prog.png');
  prog:setAnchorPoint(cc.p(0,0));
  prog:setPosition(cc.p(1,1));
  prog:setTag(1)
  progbg:addChild(prog);
  m_process=progbg;
  m_prosize=prog:getContentSize();
  m_process:setVisible(false)
  local t=0;
  local function runTxt()  
	t=t+1
	local tail={'','.','..','...'};
    m_text:setString('版本检查' .. tail[t%4+1]); 
  end  
  m_text  = cc.Label:createWithTTF(ttfConfig,'版本检查') 
  local ac=schedule(ccbnode,runTxt,0.5)
  ac:setTag(1)
  m_text:setAnchorPoint(cc.p(0,0))
  m_text:setPosition(cc.p(winsize.width/2-m_text:getContentSize().width/2,winsize.height/2))
  ccbnode:addChild(m_text)  
  m_btnOk = cc.MenuItemImage:create('res/checkversion/btn_qd_n.png','res/checkversion/btn_qd_h.png')  
  m_btnOk:setPosition(cc.p(winsize.width/2,winsize.height/2-65))
  local menu=cc.Menu:create(m_btnOk)
  menu:setPosition(cc.p(0,0))
  ccbnode:addChild(menu)   
  local function clickOk()
    local function restart()
      os.exit();
    end 
    if m_state == state_info then
      if m_needwholeversion then
        --未来可设置成跳转到appstore
        os.exit();
      else
        setState(state_loading);
      end
    elseif m_state == state_error then
      restart(); 
    end
  end 
  m_btnOk:registerScriptTapHandler(clickOk)
  m_btnOk:setVisible(false); 
  local function girlRun()  
    local total = 100; 
    m_timeindex = m_timeindex+1;
  end  
  schedule(ccbnode,girlRun,1); 
  return ccbnode;
end 
--没有的话，就将readVersion中构造的版本号保存
local function saveVersion() 
  local path = cc.FileUtils:getInstance():fullPathForFilename(gd_versionfile);
  local file = io.open(path,'wb');
  if file then 
	local json = require 'json' 
    local data = json.encode(gd_version);
    file:write(data);
    file:close();
  end
end
--先读取自己的版本号 
local function readVersion() 
  local data = readData(gd_versionfile);
  --构造一个version,防止读不到版本信息
  gd_version.versionstr = "0.1.20";
  gd_version.version = 3;
  gd_version.build = 1;
  gd_version.des = "版本介绍"; 
  if data and #data > 0 then
    gd_version = json.decode(data);
	for key,value in pairs(gd_version) do 
		print(key,value)
	end
    return true;
  end
  return false;
end
--版本检测的入口，在main.lua中调用
function Check(doaftercheckversion)  
  m_doaftercheckversion = doaftercheckversion; 
  if not readVersion() then   
    saveVersion();
  end     
  local createScene = function()
	return TuiBase:create()
  end 
  local name='checkversion'
  REGISTER_SCENE_FUNC('checkversion',createScene) 
  local objScene = LoadScene(name)
  local scene=cc.Scene:create();
  objScene:addChild(getCheckversion());
  scene:addChild(objScene);
  cc.Director:getInstance():replaceScene(scene) 
    
  if cc.PLATFORM_OS_WINDOWS == cc.Application:getInstance():getTargetPlatform() then 
	setState(state_loadingres);
  else 
	performWithDelay(objScene,checkVersion,0);
  end
end  
function setState(state)
  m_state = state;
  local alreadysize={};
  if m_state == state_info then
    m_versionindex = 1;
	m_ccbnode:stopActionByTag(1)
    m_btnOk:setVisible(true);
	m_process:setVisible(false);
    m_needwholeversion = false
    for i = 1,#m_updatevlist do
      if (m_updatevlist[i].build > gd_version.build) then
        m_needwholeversion = true;
        break;
      end
    end 
    if m_needwholeversion then
      m_text:setString('请下载最新版');
	  m_text:setPosition(cc.p(winsize.width/2-m_text:getContentSize().width/2,winsize.height/2))
    else 
      m_totolsize=0;
      for i = 1,#m_updatevlist do
        m_totolsize = m_totolsize+m_updatevlist[i].length;
      end
	  local totalsize=m_totolsize / 1024 / 1024;
	  if totalsize < 1 then --小于1M都自动下载
	    setState(state_loading);
	  else 
		m_text:setString('本游戏做了一些优化,您需要更新' .. string.format('%.3f',totalsize) .. 'M资源,点击确定更新')
		m_text:setPosition(cc.p(winsize.width/2-m_text:getContentSize().width/2,winsize.height/2))
	  end
    end
  elseif m_state == state_loading then 
    local t=0;
    local function runTxt()  
	  t=t+1
	  local tail={'','.','..','...'};
      m_text:setString('正在获取版本' .. tail[t%3+1]); 
	end  
	m_ccbnode:stopActionByTag(1)
	local ac = schedule(m_ccbnode,runTxt,0.5);
	ac:setTag(1)
    m_btnOk:setVisible(false);
	m_process:setVisible(true);
    m_text:setString('正在获取版本'); 
	m_text:setPosition(cc.p(winsize.width/2-m_text:getContentSize().width/2,winsize.height/2))
    alreadysize[m_versionindex]=0;
    local function onError(errorCode)
      if errorCode then
        setState(state_error);
      end
    end
    local function onProgress(percent)     
      m_ccbnode:stopActionByTag(1)	 
      local vinfo = m_updatevlist[m_versionindex]; 
      alreadysize[m_versionindex] = vinfo.length*percent/100;
      local asize = 0;
      for vi = 1,m_versionindex do 
        asize=asize+alreadysize[vi];
      end  
	  local prorate=asize/m_totolsize
	  local prog=m_process:getChildByTag(1);
	  prog:setTextureRect(cc.rect(0,0,prorate*m_prosize.width, m_prosize.height));
      m_text:setString('下载中' .. string.format('%.2f',prorate*100) .. '%'); 
    end 
    local function onSuccess()
      m_ccbnode:stopActionByTag(1)	
      m_versionindex = m_versionindex+1;
      alreadysize[m_versionindex]=0;
      if m_versionindex>#m_updatevlist then
		local t=0;
		local function runTxt()  
	      t=t+1
		  local tail={'','.','..','...'};
		  print('正在安装更新包' .. tail[t%3+1])
          m_text:setString('正在安装更新包' .. tail[t%3+1]); 
		end  
		m_ccbnode:stopActionByTag(1)
		local ac = schedule(m_ccbnode,runTxt,0);
		ac:setTag(1)
        m_text:setString('正在安装更新包'); 
		m_text:setPosition(cc.p(winsize.width/2-m_text:getContentSize().width/2,winsize.height/2))
		cc.FileUtils:getInstance():purgeCachedEntries()
        checkversionKit();  
        initSearchPath();--再设置一次搜索路径，不能清空原先的搜索路径
        readVersion();--刷新version
        setState(state_complete); 
      else
        startloading();
      end
    end
    c_initHotUpdate(gd_hotupdatedir,onProgress,onSuccess,onError);
    startloading();
  elseif m_state == state_error then
    m_ccbnode:stopActionByTag(1)
    m_text:setString('网络异常,请检查网络并重新进入游戏!');
	m_text:setPosition(cc.p(winsize.width/2-m_text:getContentSize().width/2,winsize.height/2))
    m_btnOk:setVisible(true);
	m_process:setVisible(false);
  elseif m_state == state_complete then 
	setState(state_loadingres); 
  elseif m_state == state_loadingres then 
	m_ccbnode:stopActionByTag(1);
    package.loaded['commonlua'] = nil; 
    m_btnOk:setVisible(false);
	m_process:setVisible(true);
	local t=0;
	local function runTxt()  
		t=t+1
		local tail={'','.','..','...'}; 
		m_text:setString('正在加载游戏' .. tail[t%3+1]); 
	end  
	m_ccbnode:stopActionByTag(1)
	local ac = schedule(m_ccbnode,runTxt,0);
	ac:setTag(1) 
    m_text:setString('正在加载游戏'); 
	m_text:setPosition(cc.p(winsize.width/2-m_text:getContentSize().width/2,winsize.height/2)) 
	-- 加载纹理,只加载登录本模块需要的东西 
	local aryRes = 
	{
	   'res/public/public1',
	   'res/public/public2',
	   'res/login/login',
	};
	
	local function loadLua()
		local index=1;
		local function loadSingle() 
			local socket=require 'socket/socket'
			local fromtime=socket.gettime();
			local tail={'','.','..','...'}; 
			m_text:setString('正在加载游戏' .. tail[index%3+1]);
			local fun=lualist[index];
			if fun then 
				fun()
			else  
				m_doaftercheckversion()
			end
			local inter=socket.gettime()-fromtime;
			print('加载index=',index,'耗时' .. inter*1000 .. '毫秒')
			index = index+1;
		end
		schedule(m_ccbnode,loadSingle,0)
	end
	local totallen=#aryRes;
	local already=0;
    local prorate=already/totallen;
	local prog=m_process:getChildByTag(1);
    prog:setTextureRect(cc.rect(0,0,prorate*m_prosize.width, m_prosize.height));
	for i,file in pairs(aryRes) do 
        local function result()  
		    already = already + 1;
			if already>=totallen then  
				performWithDelay(m_text,loadLua,0) 
			end 
		    prorate=already/totallen; 
			prog:setTextureRect(cc.rect(0,0,prorate*m_prosize.width, m_prosize.height));
        end
        cc.Director:getInstance():getTextureCache():addTextureAsync(file..".pvr.ccz",result)
    end 
  end
end 
  

